﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NSsh.Common.Packets;
using NSsh.Common.Types;
using NSsh.Server.TransportLayer;
using NSsh.Server.TransportLayer.State;

namespace NSsh.Client {

    public class ClientKeysExchangedState : AbstractTransportState {

        private bool _svcAcceptPacketReceived;
        private bool _userAuthFailurePacketReceived;
        private bool _userAuthSuccessPacketReceived;

        public override void Process(ITransportLayerManager manager) {

            manager.WritePacket(new IgnorePacket());

            ServiceRequestPacket svcReqPacket = new ServiceRequestPacket();
            svcReqPacket.ServiceName = ServiceTypeAlgorithmHelper.ToString(ServiceType.UserAuthentication);
            manager.WritePacket(svcReqPacket);

            while(!_svcAcceptPacketReceived) {
                ProcessPacket(manager);
            }

            manager.WritePacket(new IgnorePacket());

            UserAuthRequestPacket userAuthReqPacket = new UserAuthRequestPacket();
            userAuthReqPacket.ServiceName = ServiceTypeAlgorithmHelper.ToString(ServiceType.UserAuthentication);
            userAuthReqPacket.UserName = "test";
            userAuthReqPacket.AuthMethod = AuthenticationMethod.Password;
            UserAuthPasswordPayload passwordPayload = new UserAuthPasswordPayload();
            passwordPayload.Password = "password";
            userAuthReqPacket.AuthPayload = passwordPayload;
            manager.WritePacket(userAuthReqPacket);

            while (!_userAuthSuccessPacketReceived) {
                ProcessPacket(manager);
            }

            manager.ChangeState(TransportLayerState.Authenticated);
        }

        public void ServiceAcceptPacket(ITransportLayerManager manager, ServiceAcceptPacket packet) {
            _svcAcceptPacketReceived = true;
        }

        public void UserAuthFailurePacket(ITransportLayerManager manager, UserAuthFailurePacket packet) {
            _userAuthFailurePacketReceived = true;
        }

        public void UserAuthSuccessPacket(ITransportLayerManager manager, UserAuthSuccessPacket packet) {
            _userAuthSuccessPacketReceived = true;
        }
    }
}

